package org.xqh.utils.encrypt;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.compress.utils.Sets;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.xqh.utils.DateUtil;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.Map.Entry;

/**
 * @author leo
 * @description 常用加密工具类
 * @date
 */
@Slf4j
public class EncryptUtils {

    private static Logger logger = LoggerFactory.getLogger(EncryptUtils.class);

    public static final String HASH_ALGORITHM = "SHA-1";
    public static final int HASH_INTERATIONS = 1024;
    public static final int SALT_SIZE = 8;

    private final static String CHARSET_NAME = "UTF-8";

    private final static String ENCRYPT_AES = "AES";

    public final static String padding_char = "0000000000000000";//补位字符
    public final static int default_secret_len = 16;//默认秘钥长度

    public static String urlDecode(String str) {
        try {
            return URLDecoder.decode(str, CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return str;
    }

    public static String urlEncode(String str) {
        try {
            return URLEncoder.encode(str, CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * encode string
     *
     * @param str
     * @return
     */
    public static String encodeString(String str) {
        try {
            return URLEncoder.encode(str, CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            logger.error("", e);
        }
        return str;
    }

    /**
     * base64 解码
     *
     * @param str
     * @return
     */
    public static String base64Decode(String str) {
        try {
            return new String(Base64.decodeBase64(str.getBytes(CHARSET_NAME)), CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            logger.error("", e);
        }
        return str;
    }

    public static byte[] base64DecodeBytes(String key) {
        return java.util.Base64.getDecoder().decode(key);
    }

    /**
     * base64 编码
     *
     * @param encryptStr
     * @return
     */
    public static String base64Encode(String encryptStr) {
        try {
            return Base64.encodeBase64URLSafeString(encryptStr.getBytes(CHARSET_NAME));
        } catch (UnsupportedEncodingException e) {
            logger.error("", e);
        }
        return encryptStr;
    }

    public static void main(String[] args) {

//        System.out.println(urlDecode("De%20Ruijterkade%20154%2C%201011%20AC%2C%20Amsterdam.json"));
        System.out.println(urlDecode("https://api.opencagedata.com/geocode/v1/json?q=52.5432379%2C+13.4142133&key=06d3a2adfaac4a87aacd2612084bdf13"));
//        String msg = "ak=PWbK6NNtRKyEpbSg&deviceSn=EC671JJ152403EB3&ts=1751004578&SecretKey=zuGRPTHMWQUjcVm7VzLUxMc3A87YQCCu";
//        System.out.println(getSha256(msg));
//        String pwd = "Lgqbwm99PO0jE05K";
//        String salt = "mFrQhv";
//
//        String test = " 少年谢尔顿";
//        System.out.println( test.trim());
//        System.out.println(getSha256(pwd + salt));
// 24590305984cec19ca7b3eb527e38b120c82b60babad3afa949ed256504b1c1d
        //
//        System.out.println(getSha256("active_ts=1718606960&ak=EC660JJ29230465F&mac=98:6E:E8:23:86:D1&ts=1720048599&SecretKey=16VcV65ZBidVevMNSDTX9BTPGQFCYAEYMBmibVmhRXkvD0Hlj9FGWKDSTgphjq46"));//请求签名: 26b0a6a4ccfabca2f495ef5453644810fae4fe059154c0904ebc9fffe2c6eac3

//        String api = "/v1/opt/%E5%AC%B2%20%E4%B8%8B%E7%AF%87%20%E7%AC%AC20%E9%9B%86.mp3?requestUrl=/v1/link/download&key=DH-mAVc00002010PNLM-002181&file_id=1&uuid=89fe59b8-8252-4f32-89b3-e5b2eb1354d5&path=%2F.ugreen_nas%2F11429%2FOrigin%2F%E9%9F%B3%E9%A2%91%2F%E5%B0%8F%E8%8B%AE%E5%84%BF%2F%E5%AC%B2%2F%E4%B8%8B%2F%E5%AC%B2%20%E4%B8%8B%E7%AF%87%20%E7%AC%AC20%E9%9B%";
//        String m = "/v1/opt/**";
//        AntPathMatcher antPathMatcher = new AntPathMatcher();
//        System.out.println(antPathMatcher.match(m, api));
//        String cert = "vwDrnOph5aTCEivSF1PM64bI+DTpinfzZZ5DEstBa6spCtuTK3bzWYeuTX1IpVuHS7IbCjT/7Mrpquom/iT2DAYUultAnaagMvvpvi69swHMIlei6JgznTd/Wf7YviWgZefxPx8HszHQCYk0q1kVBQxhmIV98n183K8a81fegnK0xfs0Lqpi7QglqFzjBukxatUbKJy7GlETAAS+IieGfS8AZjSQ2wuzZIB99phoXURgILuDLFjliBau3MhUPbmdoVQ67a0EnZ7WTbL+umN3Xh9zoR14uZa9vaY0VuE7EdRvpKNbEqBMGglAqgAbMRczYWkcBUIOTpHfoP3Icyhn3hQBQRWpiwMs4vG5FhjhzNEWfsXS7sj5KN3B4ZSIzjPLuS6AQGhPVzE00BY8/DtTu5HJ1yJ5WJymALzrSj5aJUPUiag+YL7KXSbzmfgbeF6wH18cqy65TKH+cQmOONwVy4ZfA+nJFPiRJHXiuoJLdlzcJ53Eev5D1VbqPiUci0iVdc6fdSNOliLfXcyHm4GBjTkEpJ9tCsC3R6PYOswmZ1VeRBoUC16NLeA+f3078S6g3GiqIKV86wNExd0wG8rBuvszhHJWpwTRTgX9+NLIOVFrkEsO89utwadGi0/xqmJk2R2ZhXcp/rjMCVq1RrOyASW63X/5Me+tDvf1goQa/0pE0cuG38LldaS2b3GFNjCPFeSTQcE9FSKaHHyRSCUkk/tOfzGghnZacSLabxzkpgULW9EsMJxxoeJvZB8k7jqeo0uApt9Q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KIGcMUDrCzFpjeSBI1a/oMBOMXJg7o+R1Iq0=";
//        String aesKye = "06h8xR7FJGRnhOGfTdiPk4LlGZV9Iv9IGzseXNWrNBcngVVqT8173P4Ul7NIt9dy";
//        System.out.println(decryptRespData(cert, aesKye));
//        System.out.println(decryptRespData(key, aesKye));
//        System.out.println(decryptRespData(ca, aesKye));
//        System.out.println(base64Decode("eyJhayI6IlVHNjYxVVUxNTIzMEI3MTYiLCJtYWMiOiI5ODo2RTpFODoyMjowQzo5NSIsInRzIjoiMTc0ODk0NDYwNyIsInVnRndWZXIiOiIxLjUuMC4yNTk2Iiwic2lnbiI6ImIxYzQ3YjY3ZDMwYTBmNjkzZjEwNzQ5YWNjNjZhODA1YjBlZjMwZmQ3NjBiMTgxNjI5ZjliZTc3OTM3YzI3ZGEiLCJhbGciOiJTSEEyNTYiLCJzbiI6IlVHNjYxVVUxNTIzMEI3MTYiLCJiIjp7ImFwcCI6MCwiZW52IjowLCJkZXZpY2UiOiIiLCJ2ZXIiOiIiLCJkZXZpY2VfbGFuZ3VhZ2UiOiIiLCJpdGVtcyI6W3sibmFtZSI6IumsvOeBreS5i+WIgyIsImxhbmd1YWdlIjoiemgtQ04iLCJ5ZWFyIjoyMDE5LCJzZWFzb24iOjQsImVwaXNvZGUiOjF9XX19"));
    }

    /**
     * 加密cloud端响应数据
     *
     * @param data      元数据
     * @param secretKey 秘钥
     * @return
     */
    public static String encryptRespData(String data, String secretKey) {
        if (StringUtils.isEmpty(data)) {
            return null;
        }
        String aesKey = getAesKey(secretKey);
        return AESUtils.encryptToBase64(data, aesKey, EncryptConstants.ALGORITHM_ECB_PKCS5);
    }

    /**
     * 根据 通讯秘钥 获取AES加解密秘钥
     * 固定截取 16位字符, 少了补"0"
     *
     * @param secretKey
     * @return
     */
    public static String getAesKey(String secretKey) {
        if (StringUtils.isEmpty(secretKey)) {
            secretKey = padding_char;
        }

        if (secretKey.length() == default_secret_len) {
            return secretKey;
        }

        if (secretKey.length() < default_secret_len) {
            secretKey = secretKey + padding_char.substring(0, default_secret_len - secretKey.length());
        }

        if (secretKey.length() > default_secret_len) {
            secretKey = secretKey.substring(0, default_secret_len);
        }
        return secretKey;
    }

    /**
     * 解密响应数据 (cloud端不用)
     *
     * @param encryptData 加密数据
     * @param secretKey   秘钥
     * @return
     */
    public static String decryptRespData(String encryptData, String secretKey) {
        if (StringUtils.isEmpty(encryptData)) {
            return null;
        }
        String aesKey = getAesKey(secretKey);
        return AESUtils.decryptFromBase64(encryptData, aesKey, EncryptConstants.ALGORITHM_ECB_PKCS5);
    }

    public static void main1234(String[] args) throws Exception {
//        String text = "华为p20 pro 智能手机";
//        String encode1 = base64Encode(text);
//        String encode2 = org.apache.tomcat.util.codec.binary.Base64.encodeBase64URLSafeString(text.getBytes("UTF-8"));
//        System.out.println(encode1);
//        System.out.println(encode2);
//        System.out.println(getMd5("123456"));
//        String str = "eyJhbGciOiJIUzI1NiJ9.eyJ0ZW5hbnRUeXBlIjoiMiIsInVpZCI6ImFkbWluIiwiYWxsT3JnQ29kZSI6W10sImVtcE51bSI6bnVsbCwicG9zdGlvbkNvZGVzIjpbXSwiaXNUZW5hbnRNYW5hZ2VyIjp0cnVlLCJuYW1lIjoi566h55CG5ZGYIiwibW9iaWxlIjoiMTg5MjkzMDU2OTQiLCJ0ZW5hbnRJZCI6ImdlZWsiLCJsYW5ndWFnZSI6InpoLUNOIiwiYWxsT3JnQ29kZVBhdGgiOltdLCJlbWFpbCI6ImFkbWluQGdldGVjaC5jbiJ9.q-6jzYZl2HefPyGUPaj9UsxMrX5JPIyWY4LEF_sJOzU";
//        System.out.println(base64Decode(str));

//        HashSet<String> ids = Sets.newHashSet();
//        System.out.println(ids.add("abcd"));
//        if(ids.add("abcd")){
//            System.out.println("fffff");
//        }

//        String abc = "abcd\nfeg";
////        String efg = "abcd\rfeg";
//
//        System.out.println(abc);
////        System.out.println(efg);
//        abc = abc.replaceAll("\\n", "");
//        System.out.println(abc);
//
//        String str = "{\"mailTemplateId\":\"a49140feb374425dd74fb90388a10bb7\",\"paramsMap\":{\"currentTime\":\"2021-09-09\",\"fdUserName\":\"梁钊\",\"table\":\"<table style=\"\\&quot;color:\" #333333;border-width:=\"\" 1px;border-color:=\"\" #666666;border-collapse:=\"\" collapse;\\\"=\"\"><tbody><tr><th style=\"\\&quot;\\n\" border-style:=\"\" solid;\\n=\"\" border-width:=\"\" 1px;\\n=\"\" padding:=\"\" 8px;\\n=\"\" border-color:=\"\" #666666;\\n=\"\" background-color:=\"\" #a1d5ee;\\\"=\"\">线索名称</th><th style=\"\\&quot;\\n\" border-style:=\"\" solid;\\n=\"\" border-width:=\"\" 1px;\\n=\"\" padding:=\"\" 8px;\\n=\"\" border-color:=\"\" #666666;\\n=\"\" background-color:=\"\" #a1d5ee;\\\"=\"\">最后更新时间</th><th style=\"\\&quot;\\n\" border-style:=\"\" solid;\\n=\"\" border-width:=\"\" 1px;\\n=\"\" padding:=\"\" 8px;\\n=\"\" border-color:=\"\" #666666;\\n=\"\" background-color:=\"\" #a1d5ee;\\\"=\"\">链接</th></tr><tr><td style=\"\\&quot;\\n\" border-width:=\"\" 1px;\\n=\"\" padding:=\"\" 8px;\\n=\"\" border-style:=\"\" solid;\\n=\"\" border-color:=\"\" #666666;\\n=\"\" background-color:=\"\" #ffffff;\\n\\\"=\"\">这是线索名称1626146789</td><td style=\"\\&quot;\\n\" border-width:=\"\" 1px;\\n=\"\" padding:=\"\" 8px;\\n=\"\" border-style:=\"\" solid;\\n=\"\" border-color:=\"\" #666666;\\n=\"\" background-color:=\"\" #ffffff;\\n\\\"=\"\">2021-07-13 15:54:30</td><td style=\"\\&quot;\\n\" border-width:=\"\" 1px;\\n=\"\" padding:=\"\" 8px;\\n=\"\" border-style:=\"\" solid;\\n=\"\" border-color:=\"\" #666666;\\n=\"\" background-color:=\"\" #ffffff;\\n\\\"=\"\"><a target=\"\\&quot;_blank\\&quot;\" href=\"https://acloud-sit.tcl.com/cpms/Clue/ClueDetail/71b9befe1ec37e2e31f4101e7bbfcce5\">点击此处查看</a></td></tr></tbody></table>\"},\"systemCode\":\"cpms\",\"tenantId\":\"geek\",\"uids\":\"ex_hu.song\"}\n";
//        System.out.println(urlDecode("http://10.74.166.198:32428/api/v1/query?query=increase%28gateway_request_error_count_total%7BappMark%3D%221621327982554%22%7D%5B86399s%5D%29&start=1630684800&end=1630771199&step=119"));
//
//        System.out.println(urlEncode("query=topk(10,increase(gateway_response_count_total{appMark=\"1621327982554\",httpStatus=\"5xx\"}[86399s]))"));
//        System.out.println(fileTypeMatchFilter("abcd", "jpeg2"));
//        String str = "%7Bapp_poros_io_log%3D%22getech%22%7D%7C%3D%22BIZ_LOG%22&limit=20&start=1630481494000000000&end=1630485094000000000&log_msg_type=BIZ_LOG&direction=backward";
//        System.out.println(urlDecode(str));

//        Long ts = 1630392619000L;
//        Long tg = 1630479619280L;
//        Date date = new Date(ts);
//        System.out.println(DateUtil.formatDate(date, "yyyy-MM-dd HH:mm:ss"));
//
//        String start = "2021-08-31 14:50:19.000";
//        Date st = DateUtil.parseDate(start, "yyyy-MM-dd HH:mm:ss.SSS");
//        System.out.println(DateUtil.formatDate(st, "yyyy-MM-dd HH:mm:ss"));
//        System.out.println(new Date().getTime());
        //1630485331294
        //1630483437000000000

        String pwd = "123456";
        pwd = getMd5(getMd5(pwd));
        System.out.println(pwd);
        pwd = getMd5( "6572"+pwd );
        System.out.println(pwd);
//        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySW5mbyI6Ik5kOExHRFZiZ1lPeVFjenpUd1Qvd05kSjVDbGliM3FTZncrMkNxZjNsSjZLbm5idUsrSkZ3Z3dvWDVMWHV6S09GRGlyRW84bGVseGFIRkM0MXptd3krWkhYN3lMV1Zlc0tGYjA0YVZNWDlQVldHSTJ6dEFiWlNaRGk2WUwvY1A0R3pTTFVMK2Juc2R0eDhadFN6TzE3QT09IiwiaXNzIjoiVUdSRUVOIiwiZXhwIjoxNjQwNjg3NjIyLCJpYXQiOjE2NDA2ODA0MjJ9.pL8LVG_LfaauEOm9LrsVCjhpUx_CbGpBzQ-UeSmQWyU";



//        System.out.println(EncryptUtils.base64Decode("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJVR1JFRU4iLCJleHAiOjE2NDA2OTcwODQsInVzZXJOYW1lIjoiNjU2OSIsImlhdCI6MTY0MDY4OTg4NH0.7AwmgMk44SZ08lzYaZ79dnRQlAeGnuwnxOuK2tpApb8"));
//        System.out.println(new Date().getTime());

        String msg = "IRtgrD8fV33b9NX33AHQxTQCB2/B42URjFK5uBdIZcrDiZL/RGkFqpg1lZGOEGffhh7h2IMoV3CwKTyAxJTUlCI3czBrQWPIDBrhr/27D6BpJVSFadC8Uo2BKnEuA+kwu8CXr3epIKaZaWPNc1CzuXuT/o1g1kwLtXR0dYmev9V6ONz3BnOF00SSSSLlxGM165C2QQq/5yoF/rreByD3YaOrMzQSM90LeNFUE7ATlql8Xv+o2rvMFOznNmpOvrEDJogeJW5gDtIX7fQhpyuGSUHl29jM4aLXtihbuOdnoRPvDoXb2iqeBLvacUi++y34R5QK6Uomcj8X4pDrxPrrIw==";
    String privateKey =
        "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDY8kjweshXy8ek\n"
            + "rHyCGOW26L5HoT0L7mdPe/JL+ox3fTIMMP0PCD9ciLMD+kll2CnQGkUe6gqOsHsG\n"
            + "y0ymyFjhFP7KoBZJc9XLzGfsnVmR4n+XeZ/nTjb3haAHqY1Tz/z/inNAib1fCKiw\n"
            + "nfLBF5hOVk+BFIfishcagKrj+2uh9Qfql8sI6qGjToVvbW7ESh2RIXU8j07taiEI\n"
            + "IjaoZqciMK0f8D4dtFjvFgdkXhQhL5tAlZfSIVRsDG7YKmIzQd9oy+8RElTURc8q\n"
            + "oVETHxmgpCnHFIP5Ic/udhcg8wVaDM6aLnPH6h9w/63Z7YbsMYEih3DC6zGoTGFN\n"
            + "DMHlFBr7AgMBAAECggEAZ93wH/qZCrfM2MGgRuVGrgDWgRLoWFsG6V4tTkUhlV/C\n"
            + "Y2Xc8qJ/O31TP/dHxtPsiO7a4wcokNJbxI/3He7T5seXiUmGAhrMZGtz4iwfoyHu\n"
            + "9oXLkgG3fWBjkueRe2wb8/jEX0TS/rn1kcG9ZMc4K2FVZTaALIAZYZ3ys34/NOVq\n"
            + "THicPWpH2VvlZavoDKCV+SIUm/aLi5KcVkLg5G70dc+Oa3bZ2JsjaUnMVSu9tzin\n"
            + "eYlMP2vvqrkmkEb3+IziUNSddGKtzpQFB6DudZeeShVj6XJNiRt9+ayogX5tWnqG\n"
            + "qSJyt5gS2gD5+uZJKbk4gWJSI+TmSvw5lIZA/XYdMQKBgQD/BObmJsXgaAOBqKGr\n"
            + "VPggUom+X8H90KZIOSxjAlBoOPShTAPxn9Sh605vBowQcdw5MdPt9687scDCjtWo\n"
            + "ymil4XoSVRH9og0KnwBpOCohFf5iyxDPRkIhrTPREpLCVB0yeGvS7CG2KiCECPPO\n"
            + "jiu3fyk2P4t2f0op9HJ4ExLU8wKBgQDZx+VIy92dnwdfLOjYA+dnxtx2exDkc7I7\n"
            + "koBhA7X6/ZlQ8wnlg+UuYiB24gJjm9K0Sf/s5ZS9Aj/6od/hI46B05CRm5XNBipY\n"
            + "m1fAtosaSfuytgazRpbg77CUaZWSq6rjBt4qaHnDt4v3vxr9zp6iL2qA22IQIJe4\n"
            + "7UhaYpZD2QKBgHxMIFrXVSUurV7aGYqPzKy8biTbOYuD0jhrnYXYj+ZstFeV3Go9\n"
            + "0/7j2QPmdghh5sv9zGU1jzSSS/jIc71kgqMvhjc/PZiZDrA5lZKzbF1aAfaXMWdF\n"
            + "wF/3ssTZv6x2IREDftJ8g2XtnJGeZ28q/oXetfCaAljMbBKM8eoyqcAfAoGATMPe\n"
            + "eVuLIa1VzuGorcQqhHUfbxAQM0bo84C/ifLh6bgMm/EfcuycE055fQ5Lo0rg6bYP\n"
            + "5TRDyqAJZ1I59UUwTWkC06CRHDTpJlSTiRWPUNP1SdhJ4lWmh2FVz+qr04h5cw8P\n"
            + "rskm6qs/RjPx0rdLSYYHN6adGWwzrvbNAzcvGnkCgYEA6B2ZmQ+ffHtIxTJ7tUqT\n"
            + "JRA9rF/eD0CBoeQGF7Jdamp1I7v467DItcEwsCYmFNIoJfK+sL0tL83TuSwO9rLz\n"
            + "pl8aepjF7sekaZqo14UbLlSuD2rLO/yjxLdIbGKzH9CRhDdA1IntZ4Cu8O2vxXYP\n"
            + "KgUb2J/Kd8nOu8mmmZQ3whE=";
        System.out.println(RSAUtils.decrypt(msg, privateKey));
    }

    public static String fileTypeMatchFilter = "jpg#jpeg,jpg3#jpeg2#abcd";

    public static boolean fileTypeMatchFilter(String typeName, String suffix){
        if(org.apache.commons.lang3.StringUtils.isEmpty(fileTypeMatchFilter)){
            return false;
        }

        if(!fileTypeMatchFilter.contains("#")){
            return false;
        }

        String[] filterArr = fileTypeMatchFilter.split(",");

        for(String filter:filterArr){
            if(!filter.contains("#")){
                continue;
            }
            List<String> item = Lists.newArrayList(filter.split("#"));
            if(CollectionUtil.isEmpty(item) || item.size() < 2){
                continue;
            }

            Optional<String> typeOpt = item.stream().filter(i-> i.equalsIgnoreCase(typeName)).findAny();
            Optional<String> suffixOpt = item.stream().filter(i-> i.equalsIgnoreCase(suffix)).findAny();
            if(typeOpt.isPresent() && suffixOpt.isPresent()){
                return true;
            }
        }
        return false;
    }

    /**
     * 用户密码加密
     *
     * @param password
     * @return
     */
    public static String encryPwd(String password) {
        return getMd5(getSha1(password));
    }

    /**
     * 参数 按ascii码排序 拼接
     *
     * @param params
     * @return
     */
    public static String buildSignStr(Map<String, Object> params) {
        StringBuilder sb = new StringBuilder();
        // 将参数以参数名的字典升序排序
        Map<String, Object> sortParams = new TreeMap<>(params);
        // 遍历排序的字典,并拼接"key=value"格式
        for (Map.Entry<String, Object> entry : sortParams.entrySet()) {
            if (sb.length() != 0) {
                sb.append("&");
            }
            sb.append(entry.getKey()).append("=").append(entry.getValue());
        }
        return sb.toString();
    }


    public static String getSha1(String string) {
        return DigestUtils.sha1Hex(string);
    }

    public static String getSha256(String string) {
        return DigestUtils.sha256Hex(string);
    }

    public static String getMd5(String str) {
        return DigestUtils.md5Hex(str);
    }

    /**
     * 敏识 token 加密
     *
     * @param key
     * @param token
     * @return
     */
    public static String getMinshiToken(String key, MinshiToken token) {
        SecretKeySpec keySpec = new SecretKeySpec(java.util.Base64.getDecoder().decode(key), ENCRYPT_AES);
        ObjectMapper jsonMapper = new ObjectMapper();
        try {
            Cipher cipher = Cipher.getInstance(ENCRYPT_AES);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            return java.util.Base64.getEncoder().encodeToString(
                    cipher.doFinal(jsonMapper.writeValueAsBytes(token)));
        } catch (NoSuchAlgorithmException e) {
            logger.error("", e);
        } catch (NoSuchPaddingException e) {
            logger.error("", e);
        } catch (InvalidKeyException e) {
            logger.error("", e);
        } catch (BadPaddingException e) {
            logger.error("", e);
        } catch (JsonProcessingException e) {
            logger.error("", e);
        } catch (IllegalBlockSizeException e) {
            logger.error("", e);
        }
        return null;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class MinshiToken {

        private String userName;

        private Long validTimeStart;

        private Long validTimeEnd;
    }


    /**
     * SHA1 加密
     *
     * @param str
     * @return
     */
    public static String encryptCalc(String str, String encryType) {
        if (null == str || 0 == str.length()) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance(encryType);
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (NoSuchAlgorithmException e) {
            logger.error("", e);
        } catch (UnsupportedEncodingException e) {
            logger.error("", e);
        }
        return null;
    }

    /**
     * 生成RSA签名
     */
    public static String handleRSA(TreeMap<String, Object> map,
                                   String privateKey) {
        StringBuffer sbuffer = new StringBuffer();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sbuffer.append(entry.getValue());
        }
        String signTemp = sbuffer.toString();

        String sign = "";
        if (StringUtils.isNotEmpty(privateKey)) {
            sign = RSAUtils.sign(signTemp, privateKey);
        }
        return sign;
    }

    /**
     * 返回的结果进行验签
     *
     * @param data             业务数据密文
     * @param encrypt_key      对ybAesKey加密后的密文
     * @param clientPublicKey  客户端公钥
     * @param serverPrivateKey 服务器私钥
     * @return 验签是否通过
     * @throws Exception
     */
    public static boolean checkDecryptAndSign(String data, String encrypt_key,
                                              String clientPublicKey, String serverPrivateKey) throws Exception {

        /** 1.使用serverPrivateKey解开aesEncrypt。 */
        String AESKey = "";
        try {
            AESKey = RSAUtils.decrypt(encrypt_key, serverPrivateKey);
        } catch (Exception e) {
            /** AES密钥解密失败 */
            log.error("AES秘钥解密失败", e);
            return false;
        }

        /** 2.用aeskey解开data。取得data明文 */
        String realData = ConvertUtils.hexStringToString(AESUtils.decryptFromBase64(data, AESKey, EncryptConstants.ALGORITHM_ECB_PKCS5));

        TreeMap<String, String> map = JSON.parseObject(realData,
                new TypeReference<TreeMap<String, String>>() {
                });

        /** 3.取得data明文sign。 */
        String sign = StringUtils.trimToEmpty(map.get("sign"));

        /** 4.对map中的值进行验证 */
        StringBuffer signData = new StringBuffer();
        Iterator<Entry<String, String>> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<String, String> entry = iter.next();

            /** 把sign参数隔过去 */
            if (StringUtils.equals(entry.getKey(), "sign")) {
                continue;
            }
            signData.append(entry.getValue() == null ? "" : entry.getValue());
        }

        /** 5. result为true时表明验签通过 */
        boolean result = RSAUtils.checkSign(signData.toString(), sign, clientPublicKey);

        return result;
    }

    /**
     * 生成hmac
     */
    public static String handleHmac(TreeMap<String, String> map, String hmacKey) {
        StringBuffer sbuffer = new StringBuffer();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            sbuffer.append(entry.getValue());
        }
        String hmacTemp = sbuffer.toString();

        String hmac = "";
        if (StringUtils.isNotEmpty(hmacKey)) {
            hmac = Digest.hmacSHASign(hmacTemp, hmacKey, Digest.ENCODE);
        }
        return hmac;
    }
}
